<?php

namespace app\common\component;

use app\Request;

class Upload
{

    protected $uploadOss = true;

    protected $platformId = '';

    protected $allow = ['jpg', 'jpeg', 'png', 'gif','xlsx', 'xls', 'doc', 'docx'];

    protected $path = [
        'img' => [
            'path' => './uploads/picture/',
            'maxsize' => 10 ,//M
            'allow'=>['jpg', 'jpeg', 'png']
        ],
        'sound' => [
            'path' => './uploads/sound/',
            'maxsize' => 2 //M
        ],
        'file' => [
            'path' => './uploads/file/',
            'maxsize' => 50
        ],
        'video' => [
            'path' => './uploads/video/',
            'maxsize' => 50
        ]
    ];

    /**
     * @return self
     */
    public static function instance()
    {
        static $_instance = [];
        if (empty($_instance)) {
            $_instance = new self();
        }
        return $_instance;
    }

    public function uploadFile()
    {
        if (empty($_FILES))
            return error('没有文件上传');
        foreach ($_FILES as $file) {
            if ($file['error']) {
                return error('文件上传失败');
            }
            $extName = ltrim(strtolower(strrchr($file['name'], '.')), '.');
            $name = (date('YmdHis')). '_' . (rand(1000, 9999)) . '.' . $extName;
            $type = 'file' ;
            if(in_array($extName , $this->path['img']['allow'])) $type = 'img' ;
            if(!$this->verifyMaxsize($file['size'] , $type , false)){
                return error('上传的文件超出大小限制,只能上传'.$this->path[$type]['maxsize'].'M');
            }

            $this->verifySuffix($extName);

            $path = $this->getPath($type);
            $filename = $path.$name;
            move_uploaded_file($file['tmp_name'], $filename);
            $filename = ltrim($filename, '.');
            $data = [
                'state' => 'SUCCESS',
                'type' => '.' . $extName,
                'url' => $filename
            ];
        }
        return success($data);

    }

    public function uploadBase64($base64, $platformId = '', $type = 'img', $suffix = 'jpg', $path = '')
    {
        $this->platformId = $platformId;
        if (!isset($this->path[$type]))
            ajaxError('请指定上传文件类型');
        if (empty($suffix)) {
            $suffix = 'jpg';
        }
        $this->verifySuffix($suffix);
        $base64 = preg_replace('/data:\w+\/\w+;base64,/', '', $base64);
        $code = str_replace(" ", "+", $base64);

        $this->verifyMaxsize(strlen($code), $type);

        $path = $this->getPath($type);

        $name = (date('YmdHis')) . '_' . (rand(100, 999)) . '.' . $suffix;
        $filename = $path . $name;
        file_put_contents($filename, base64_decode($code));
        /*if ($this->uploadOss) {
            $uploadResult = OssClients::instance()->uploadFile($filename, $platformId);
            if ($uploadResult['error']) {
                return error($uploadResult['msg']);
            }
            $filename = $uploadResult['data'];
        } else {
            $filename = ltrim($filename, '.');
        }*/
        $filename = ltrim($filename, '.');
        return success($filename);
    }

    public function setUploadOss($bool)
    {
        $this->uploadOss = $bool;
    }

    private function getPath($type)
    {
        $path = $this->path[$type]['path'] . ($this->platformId ? $this->platformId . '/' : '') . date('Ym') . '/';
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        return $path;
    }

    private function verifySuffix($suffix, $ajax = true)
    {
        if (!in_array(strtolower($suffix), $this->allow)) {
            if ($ajax) {
                ajaxError('不被允许的文件类型');
            }
            return false;
        }
        return true;
    }

    private function verifyMaxsize($size, $type, $ajax = true)
    {
        $maxSize = $this->path[$type]['maxsize'] * 1024 * 1024;
        if ($size > $maxSize) {
            if ($ajax)
                ajaxError('上传的文件超出限制,请重新调整图片大小，只能上传' . $this->path[$type]['maxsize'] . 'M');
            return false;
        }
        return true;
    }


}

